package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private SetmealMapper setmealMapper;
    /**
     *  新增菜品和口味
     * 涉及多个数据表的设计
     * @param dishDTO
     */
    @Transactional//事务注解
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //向菜品表插入一条数据
        dishMapper.insert(dish);
        //获取Insert生成的主键id
        Long id = dish.getId();
        //向口味表插入n条数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size()> 0){
            //给每个口味赋值上id
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(id);
            });
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 菜品批量删除
     * @param ids
     * @return
     */
    @Transactional//涉及多个数据表要加上事务注解，以确保数据的一致性，隔离性。
    public void deleteBatch(List<Long> ids) {
        //1.判断菜品是否起售或禁售，再决定是否删除
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if (dish.getStatus() == StatusConstant.ENABLE){
                //如果为起售状态就抛出不可删除异常
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //2.判断菜品是否关联套餐，再决定是否删除
        List<Long> setmealId = setmealDishMapper.getSetmealIdByDishId(ids);
        if (setmealId != null && setmealId.size()>0){
            //当前菜品关联的套餐，抛出异常
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //3.删除菜品表中的菜品
/*        for (Long id : ids) {
            dishMapper.deleteById(id);
            //4.删除菜品关联的口味数据
            dIshFlavorMapper.deleteByDishId(id);
            //每次遍历一个id就发一条sql语句，当id数量很多时会引起性能的问题
            //故进行优化，使用一条sql就删除所有要删除id对应的菜品表，另外一个也同理

        }*/
        //delete from dish where id in (?,?,?)
        dishMapper.deleteByIds(ids);
        //delete from dish_flavor where dish_id in (?,?,?)
        dishFlavorMapper.deleteByDishIds(ids);

    }

    /**
     * 按菜品id来获取菜品与口味数据
     * @param id
     * @return
     */
    public DishVO getDishWithFlavorById(Long id) {
        //1.按照菜品id过去对应菜品表
        Dish dish = dishMapper.getById(id);
        //2.按照菜品获取对应口味表
        List<DishFlavor> flavors = dishFlavorMapper.getByDishId(id);
        //3.将获取到的数据封装到DishVo中
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(flavors);
        return dishVO;
    }

    /**
     *  根据id修改对应的菜品和口味信息
     * @param dishDTO
     * @return
     */
    public void updateWithFlavor(DishDTO dishDTO) {
        //口味的修改可能有三种，未改，删除再改，添加口味
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //修改菜品基本信息
        dishMapper.update(dish);
        //可以先将所有的口味删除，在进行插入操作
        //删除菜品id关联的所有口味数据
        dishFlavorMapper.deleteByDishId(dishDTO.getId());

        //重新插入口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size()> 0) {
            //给每个口味赋值上id
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
            //向口味插入n调数据
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        //查询菜品，按前端传入的菜品对象查询
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();//为菜品和口味表联合创建DishVO对象

        for (Dish d : dishList) {//挨个从dish中按dishid去查找口味
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());
            //将菜品数据和口味数据封装到dishVo中
            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    /**
     * 启用、禁用分类
     * @param status
     * @param id
     */
    public void startOrStop(Integer status, Long id) {
        Dish dish = new Dish();
        dish.setStatus(status);
        dish.setId(id);
        dishMapper.update(dish);
    }
}
